<template>
  <div class="appointment-list">
    <div class="header">
      <el-icon class="back-icon" @click="router.back()">
        <ArrowLeft />
      </el-icon>
      <span class="title">我的预约</span>
    </div>

    <div class="content" v-loading="loading">
      <el-empty v-if="appointments.length === 0" description="暂无预约记录" />

      <div v-else class="appointment-items">
        <div v-for="appointment in appointments" :key="appointment.id" class="appointment-item">
          <div class="appointment-info">
            <div class="info-row">
              <span class="label">预约日期：</span>
              <span class="value">{{ formatDate(appointment.start_time) }}</span>
            </div>
            <div class="info-row">
              <span class="label">预约原因：</span>
              <span class="value">{{ getReasonByAppointment(appointment) }}</span>
            </div>
            <div class="info-row">
              <span class="label">时长：</span>
              <span class="value">{{ appointment.duration }}分钟</span>
            </div>
            <div class="info-row">
              <span class="label">预约人：</span>
              <span class="value">{{ appointment.user_name || '-' }}</span>
            </div>
            <div class="info-row">
              <span class="label">联系电话：</span>
              <span class="value">{{ appointment.user_phone || '-' }}</span>
            </div>
            <div class="info-row">
              <span class="label">咨询师：</span>
              <span class="value">{{ appointment.counselor_name || '-' }}</span>
            </div>
            <div class="info-row">
              <span class="label">咨询师电话：</span>
              <span class="value">{{ appointment.counselor_phone || '-' }}</span>
            </div>
            <div class="info-row">
              <span class="label">预约时间：</span>
              <span class="value">{{ formatDateTime(appointment.start_time) }} ~ {{ formatDateTime(appointment.end_time) }}</span>
            </div>
            <div class="info-row">
              <span class="label">状态：</span>
              <el-tag :type="getStatusType(appointment.status)">
                {{ getStatusText(appointment.status) }}
              </el-tag>
            </div>
            <div v-if="appointment.cancel_reason" class="info-row">
              <span class="label">取消原因：</span>
              <span class="value">{{ appointment.cancel_reason }}</span>
            </div>
          </div>

          <div class="actions">
            <el-button
              v-if="canCancel(appointment)"
              type="danger"
              size="small"
              @click="handleCancel(appointment)"
            >
              取消预约
            </el-button>
            <el-button
              v-if="userStore.user?.is_counselor && appointment.counselor_id === userStore.user.id && appointment.status !== 'confirmed'"
              type="primary"
              size="small"
              @click="confirmAppointment(appointment)"
            >
              确认预约
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'
import { Api } from '@/api'
import { useUserStore } from '@/stores/user.js'

const router = useRouter()
const userStore = useUserStore()
const loading = ref(false)
const appointments = ref([])
const consultationRoomList = ref([])

// 获取预约列表
const fetchAppointments = async () => {
  loading.value = true
  try {
    const response = await Api.getAllAppointments()
    if (response.data.status === 200) {
      const all = response.data.data.appointments
      const myId = userStore.user?.id
      if (userStore.user?.is_counselor) {
        // 咨询师：看自己预约和counselor_id等于自己id的
        appointments.value = all.filter(a => a.user_id === myId || a.counselor_id=== myId)
      } else {
        // 普通用户：只能看自己预约
        appointments.value = all.filter(a => a.user_id === myId)
      }
    } else {
      throw new Error(response.data.message || '获取预约列表失败')
    }
  } catch (error) {
    console.error('获取预约列表失败:', error)
    ElMessage.error('获取预约列表失败，请稍后再试')
  } finally {
    loading.value = false
  }
}

const fetchConsultationRoomList = async () => {
  try {
    const res = await Api.getConsultationRoomInfo()
    if (res.data.status === 200) {
      consultationRoomList.value = res.data.data.rooms
    }
  } catch {
    // 错误处理
  }
}

const getReasonByAppointment = (appointment) => {
  return (
    consultationRoomList.value.find(
      room =>
        new Date(room.appointment_date).toISOString().slice(0, 10) === new Date(appointment.appointment_date || appointment.start_time).toISOString().slice(0, 10) &&
        room.user && appointment.user_id && room.user.id === appointment.user_id
    )?.reason || '-'
  )
}

// 获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case 'completed':
      return 'success'
    case 'pending':
      return 'warning'
    case 'canceled':
      return 'info'
    default:
      return 'info'
  }
}

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 'completed':
      return '已完成'
    case 'pending':
      return '待确认'
    case 'canceled':
      return '已取消'
    default:
      return status
  }
}

// 判断是否可以取消预约
const canCancel = (appointment) => {
  const appointmentDate = new Date(appointment.start_time)
  const now = new Date()
  // 只能取消未来的预约且状态为 pending 或 confirmed
  return appointmentDate > now && (appointment.status === 'pending' || appointment.status === 'confirmed')
}

// 取消预约
const handleCancel = async (appointment) => {
  try {
    if (!userStore.userId) {
      ElMessage.error('用户信息不存在，请重新登录')
      return
    }

    await ElMessageBox.confirm(
      '确定要取消该预约吗？',
      '取消预约',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await Api.cancelConsultation({
      id: appointment.id,
      user_id: userStore.userId
    })

    if (response.data.status === 200) {
      ElMessage.success('预约已取消')
      fetchAppointments() // 刷新列表
    } else {
      throw new Error(response.data.message || '取消预约失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消预约失败:', error)
      ElMessage.error('取消预约失败，请稍后再试')
    }
  }
}

// 确认预约
const confirmAppointment = async (appointment) => {
  try {
    const response = await Api.confirmConsultation({
      id: appointment.id,
      user_id: userStore.user.id,
    })
    if (response.data.status === 200) {
      ElMessage.success('预约已确认')
      fetchAppointments()
    } else {
      throw new Error(response.data.message || '确认预约失败')
    }
  } catch (error) {
    ElMessage.error('确认预约失败，请稍后再试')
  }
}

const formatDateTime = (dt) => {
  if (!dt) return '-'
  if (typeof dt === 'string' && dt.includes('T')) {
    return dt.replace('T', ' ').replace('Z', '').slice(0, 16)
  }
  const d = new Date(dt)
  const pad = n => n.toString().padStart(2, '0')
  return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`
}

const formatDate = (dt) => {
  if (!dt) return '-'
  if (typeof dt === 'string' && dt.includes('T')) {
    return dt.split('T')[0]
  }
  const d = new Date(dt)
  const pad = n => n.toString().padStart(2, '0')
  return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())}`
}

onMounted(() => {
  fetchAppointments()
  fetchConsultationRoomList()
})
</script>

<style scoped>
.appointment-list {
  background-color: #f7f8fa;
  min-height: 100vh;
}

.header {
  display: flex;
  align-items: center;
  padding: 10px 16px;
  background-color: white;
  border-bottom: 1px solid #f0f0f0;
}

.back-icon {
  font-size: 20px;
  cursor: pointer;
  margin-right: 16px;
}

.title {
  font-size: 16px;
  font-weight: 500;
}

.content {
  padding: 16px;
}

.appointment-items {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.appointment-item {
  background-color: white;
  border-radius: 8px;
  padding: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.appointment-info {
  flex: 1;
}

.info-row {
  margin-bottom: 8px;
  display: flex;
  align-items: center;
}

.info-row:last-child {
  margin-bottom: 0;
}

.label {
  color: #666;
  width: 80px;
  flex-shrink: 0;
}

.value {
  color: #333;
}
</style>
